#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>

void *thmain1(void *arg); // 线程1的主函数
void *thmain2(void *arg); // 线程2的主函数

int main(int argc, char *argv[])
{
    pthread_t thid1 = 0, thid2 = 0;

    if (pthread_create(&thid1, NULL, thmain1, NULL) != 0)
    {
        printf("pthread_create failed.\n");
        exit(-1);
    }
    if (pthread_create(&thid2, NULL, thmain2, NULL) != 0)
    {
        printf("pthread_create failed.\n");
        exit(-1);
    }

    sleep(10);
    void *ret;

    // 等待子线程退出。
    printf("join...\n");
    int result = 0;             // 用于存放join的返回值
    result = pthread_join(thid2, &ret);
    printf("thid2 result=%d,ret=%ld\n", result, ret);
    result = pthread_join(thid1, &ret);
    printf("thid1 result=%d,ret=%ld\n", result,ret);

    ret = 0;

    result = pthread_join(thid2, &ret);
    printf("thid2 result=%d,ret=%ld\n", result, ret);
    result = pthread_join(thid1, &ret);
    printf("thid1 result=%d,ret=%ld\n", result,ret);

    printf("join ok.\n");
}

void *thmain1(void *arg)
{
    for(int i = 0; i < 3; ++i){
        sleep(1);
        printf("pthmain1 sleep(%d) ok.\n", i+1);
    }
    return (void*)1;
}

void *thmain2(void *arg)
{
    for(int i = 0; i < 5; ++i){
        sleep(1);
        printf("pthmain2 sleep(%d) ok.\n", i+1);
    }
    return (void*)2;
}